/*
 * File: LoadTrip.java Author: Robert Bittle <guywithnose@gmail.com>
 */
package triperest.servlets;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import triperest.Destination;
import triperest.Trip;
import triperest.TriperestUser;

/**
 * The Class LoadTrip.
 */
public class LoadTrip extends HttpServlet {

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest
	 * , javax.servlet.http.HttpServletResponse)
	 */
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		TriperestUser user = new TriperestUser(req);
		Trip trip = null;
		String param = req.getParameter("trip");
		if (param.equals("null")) {
			if (!user.getTrips().isEmpty())
				trip = user.getTrips().get(0);
		} else
			trip = new Trip(Long.valueOf(param));
		try {
			if (trip != null) {
				JSONObject retVal = new JSONObject();
				retVal.put("name", trip.getName());
				retVal.put("description", trip.getDescription());
				retVal.put("mine", trip.isThisMine(user));
				JSONArray destinations = new JSONArray();
				ArrayList<Destination> dests = trip.getDestinations();
				for (int i = 0; i < dests.size(); i++) {
					destinations.put(new JSONObject().put("id",
							dests.get(i).getID()).put("name",
							dests.get(i).getName()));
				}
				retVal.put("destinations", destinations);
				resp.getWriter().append(retVal.toString());
			}
		} catch (JSONException e) {
			// Do Nothing
		}
	}
}
